package com.example.new1;

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.os.Looper;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.util.StringTokenizer;
import android.os.Handler;
import android.os.Message;

public class MainActivity extends AppCompatActivity {
    TextView receive_server;
    EditText ed_ip;
    EditText ed_port;
    Button b_connect;
    Button b_end;
    ClientThread clientThread;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        findView();
        setListener();
    }
    private void findView(){
        receive_server=findViewById(R.id.tx_recv);
        ed_ip=findViewById(R.id.pass_ip);
        ed_port=findViewById(R.id.pass_port);
        b_connect=findViewById(R.id.button_cnet);
        b_end=findViewById(R.id.button_end);
    }
    Handler handler=new Handler(Looper.getMainLooper()){
        public void handleMessage(Message msg){

        }
    };
    //监听
    private void setListener(){
        //连接监听函数
        b_connect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ed_ip.getText().toString().equals("")||ed_port.getText().toString().equals("")){
                    Toast.makeText(MainActivity.this,"请先设置IP地址与端口号",Toast.LENGTH_SHORT).show();;
                }else {

                    String msg_ip=null;
                    String msg_port_string=null;
                    int msg_port_int=0;

                    msg_ip=ed_ip.getText().toString();
                    msg_port_string =ed_port.getText().toString();
                    msg_port_int=Integer.parseInt(msg_port_string);

                    Toast.makeText(MainActivity.this,"ip为"+msg_ip+"端口号为"+msg_port_int,Toast.LENGTH_SHORT).show();
                    clientThread=new ClientThread(handler,msg_ip,msg_port_int);
                    new Thread(clientThread).start();
                }
            }
        });
        //中断监听函数
        b_end.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    Message msg=new Message();
                    msg.obj="exit";
                    clientThread.revHandler.sendMessage(msg);
                    Toast.makeText(MainActivity.this,"与机器人连接断开",Toast.LENGTH_SHORT).show();
                }
                catch (Exception e){
                    e.printStackTrace();
                }
            }
        });
    }


}